//
//  File.swift
//  SSComment
//
//  Created by 松松 on 2019/4/24.
//

import Foundation
import Alamofire
import UIKit



var REQUEST_HEADER : [String:String]?{
    return commentBaseHeader
}

var BASE_URL : String{
    return commentBaseURL
}

var commentBaseURL = "http://192.168.3.200/"
var commentBaseHeader : [String:String]? = ["Z-APP" : "10010013"]

public class SSComment{
    static public func setUrlAndHeader(url:String,header:[String:String]?){
        commentBaseURL = url
        commentBaseHeader = header
    }
}

class SSCommentNetWork {

    static public func request(url: String, method: HTTPMethod = .get, parameter: [String:Any]?, encoding: ParameterEncoding = URLEncoding.default,success:@escaping (Any)->Void,failure:@escaping (CommentError)->Void){
        let finalUrl = (BASE_URL + url).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        Alamofire
            .request(finalUrl,
                     method: method,
                     parameters: parameter,
                     encoding: encoding,
                     headers: REQUEST_HEADER)
            .validate()
            .responseJSON { (res) in
                
                ssFunc {
                    
                    ssPrint("请求地址：",finalUrl)
                    ssPrint("方法：\(res.request!.httpMethod!)")
                    ssPrint("请求头：\(res.request?.allHTTPHeaderFields ?? [:])")
                    ssPrint("参数：",parameter ?? [:])
                    let value = res.value ?? "无"
                    if value is String{
                        ssPrint("返回值：",value)
                    }else if value is Bool{
                        ssPrint("返回值：",value)
                    }else if value is Int{
                        ssPrint("返回值：",value)
                    }else if value is Double{
                        ssPrint("返回值：",value)
                    }else{
                        if let jsonData = try? JSONSerialization.data(withJSONObject: res.value ?? [], options: .prettyPrinted){
                            let json = String(data: jsonData, encoding: .utf8)

                            ssPrint("返回值：",json ?? "无")

                        }
                    }
                }

                switch res.result{
                case .success(let value):
                    success(value)

                case .failure(_):
                    ssFunc {
                        let responseState = res.response?.statusCode ?? 10011
                        switch responseState{
                        case 400:
                            ssPrint("参数错误")
                        case 500:
                            ssPrint("未知错误")
                        default:break
                        }
                    }
                    if let serverData = res.data{
                        let json = try? JSONSerialization.jsonObject(with: serverData, options: JSONSerialization.ReadingOptions.allowFragments)
                        let jsonStr = String(data: serverData, encoding: .utf8)
                        ssPrint(jsonStr ?? "")
                        if json != nil{
                            let commentError = CommentError(fromDictionary: json as! [String:Any])
                            failure(commentError)
                        }
                    }
                }
        }
    }


    static public func post(url: String, method: HTTPMethod = .post, parameter: [String:Any]?, encoding: ParameterEncoding = URLEncoding.default,success:@escaping (Any)->Void,failure:@escaping (CommentError)->Void){
        let finalUrl = (BASE_URL + url).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        Alamofire
            .request(finalUrl,
                     method: method,
                     parameters: parameter,
                     encoding: encoding,
                     headers: REQUEST_HEADER)
            .validate()
            .responseJSON { (res) in
                ssPrint("请求地址：\(finalUrl)")
                ssPrint("方法：\(res.request!.httpMethod!)")
                ssPrint("请求头：\(res.request?.allHTTPHeaderFields ?? [:])")
                ssPrint("参数：\(parameter ?? [:])")

                let value = res.value ?? "无"
                if value is String{
                    ssPrint("返回值：",value)
                }else if value is Bool{
                    ssPrint("返回值：",value)
                }else if value is Int{
                    ssPrint("返回值：",value)
                }else if value is Double{
                    ssPrint("返回值：",value)
                }else{
                    if let jsonData = try? JSONSerialization.data(withJSONObject: res.value ?? [], options: .prettyPrinted){
                        let json = String(data: jsonData, encoding: .utf8)

                        ssPrint("返回值：",json ?? "无")

                    }
                }

                switch res.result{
                case .success(let value):
                    success(value)

                case .failure( _):
                    ssFunc {
                        let responseState = res.response?.statusCode ?? 10011
                        switch responseState{
                        case 400:
                            ssPrint("参数错误")
                        case 500:
                            ssPrint("未知错误")
                        default:break
                        }
                    }
                    if let serverData = res.data{
                        let json = try? JSONSerialization.jsonObject(with: serverData, options: JSONSerialization.ReadingOptions.allowFragments)
                        let jsonStr = String(data: serverData, encoding: .utf8)
                        ssPrint(jsonStr ?? "")
                        if json != nil{
                            let commentError = CommentError(fromDictionary: json as! [String:Any])
                            failure(commentError)
                        }
                    }
                }
        }
    }

}


